﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if DOT_NET
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif
using StyleMVVM.UnitTests.TestClasses.SimpleObjects;
using StyleMVVM.Utilities;

namespace StyleMVVM.UnitTests.Utilities
{
	[TestClass]
	public class WeakFuncTests
	{
		public class WeakFuncHelper
		{
			public WeakFunc<int> WeakFunc
			{
				get { return new WeakFunc<int>(() => ++Count); }
			}

			public int Count { get; set; }
		}

		public class WeakGenericFuncHelper
		{
			public WeakFunc<int, int> WeakFunc
			{
				get
				{
					return new WeakFunc<int, int>((x) =>
						                              {
							                              Count += x;
							                              return Count;
						                              });
				}
			}

			public int Count { get; set; }
		}

		[TestMethod]
		public void WeakFuncReleaseTest()
		{
			WeakFuncHelper helper = new WeakFuncHelper();

			WeakFunc<int> weakFunc = helper.WeakFunc;

			Assert.AreEqual(0, helper.Count);

			Assert.AreEqual(1, weakFunc.Execute());
			Assert.AreEqual(1, helper.Count);

			WeakReference weakReference = new WeakReference(helper);

			helper = null;

			GC.Collect();
			GC.WaitForPendingFinalizers();

			Assert.IsFalse(weakReference.IsAlive);
			Assert.IsFalse(weakFunc.IsAlive);
		}

		[TestMethod]
		public void WeakGeanericFuncTest()
		{
			WeakGenericFuncHelper helper = new WeakGenericFuncHelper();

			WeakFunc<int, int> weakFunc = helper.WeakFunc;

			Assert.AreEqual(0, helper.Count);

			Assert.AreEqual(2, weakFunc.Execute(2));
			Assert.AreEqual(2, helper.Count);

			WeakReference weakReference = new WeakReference(helper);

			helper = null;

			GC.Collect();
			GC.WaitForPendingFinalizers();

			Assert.IsFalse(weakReference.IsAlive);
			Assert.IsFalse(weakFunc.IsAlive);
		}
	}
}